package net.zjitc.utils.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/11/9.
 */
public class C3P0Utils {
    public static DataSource ds = null;
    //不同的线程，用不同的连接，解决方法：一个线程，保存一个conn
    public static ThreadLocal<Connection> th =new ThreadLocal<Connection>();

    static {
        ds = new ComboPooledDataSource("zjitc");
    }
    public static DataSource getDataSource(){
        return ds;
    }
    //th里面保存的是当前线程的连接对象
    public static Connection getConnection() throws SQLException {
        Connection conn = th.get();
        if (conn != null){
            return conn;  //带事务的连接
        }
       return ds.getConnection(); //此连接不带事务
    }

    //开启一个事务
    public static void startTransation() throws SQLException {
        Connection conn = th.get();
        if (conn!=null){
            throw new RuntimeException("事务已经开启，不需要再开启");
        }
        //获得一个连接，并存在th里面
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        th.set(conn);
    }

    //提交事务
    public static void commitTransation() throws SQLException {
        Connection conn = th.get();
        if (conn==null){
            throw new RuntimeException("本身没有事务，无法提交");
        }
        conn.commit();
        conn.close();
        conn = null;
        th.remove();
    }

    //回滚操作
    public static void rollbackTransation() throws SQLException {
        Connection conn = th.get();
        if (conn==null){
            throw new RuntimeException("本身没有事务，无法回滚");
        }
        conn.rollback();
        conn.close();
        conn = null;
        th.remove();
    }
    //关闭
    public static void closeConnection(Connection connection) throws SQLException {
        Connection conn = th.get();
        if (conn!= connection){  //只关闭普通的连接，带事务的连接在提交或回滚的时候关闭
            connection.close();
        }
    }

}
